#include <iostream>
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
using namespace std;
void useage(std::string &process)
{
    std::cout << "usage" << process << " server_ip server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    std::string use = argv[0];
    if (argc != 3)
    {
        useage(use);
        return 1;
    }
         std::string serverip=argv[1];
     uint16_t port=atoi(argv[2]);
     //1.创建socket
     int _sock = socket(AF_INET, SOCK_DGRAM, 0);
     if (_sock < 0)
    {
        std::cerr << "socket error: " << strerror(errno) << std::endl;
        return 2;
    }
    std::cout << "create socket success: " << _sock << std::endl;
     struct sockaddr_in server;
        memset(&server,0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());
        // while(true)
        // {
        //     std::string inbuffer;
        //     std::cout<<"please Enter#";
        //     getline(std::cin,inbuffer);
        //     ssize_t n=sendto(_sock,inbuffer.c_str(),inbuffer.size(),0,(struct sockaddr *)&server,sizeof(server));
        //     cout<<n<<endl;
        //     if(n>0)
        //     {
        //         char buffer[1024];
        //         struct sockaddr_in temp;
        //         socklen_t len = sizeof(temp);
        //         ssize_t m = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        //         cout<<"成功"<<endl;
        //         if(m > 0)
        //     {
        //         buffer[m] = 0;
        //         std::cout << "server echo# " << buffer << std::endl;
        //     }
        //     else
        //         break;
        //     }
        //     else
        //     break;
        // }
            char buffer[1024];
    while (true)
    {
        std::string inbuffer;
        std::cout << "please Enter#";
        getline(std::cin, inbuffer);
        cout << inbuffer << endl;
        size_t n = sendto(_sock, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&server, sizeof(server));
        cout << "n=:"<<n << endl;
        if (n > 0)
        {
 
            struct sockaddr_in temp;
            memset(&temp, 0, sizeof(temp));
            socklen_t len = sizeof(temp);
           ssize_t s=recvfrom(_sock, buffer, 1023, 0, (struct sockaddr*)&temp, &len);
           cout << s << endl;
           if (s > 0)
           {
            buffer[s]=0;
               std::cout << "server echo# " << buffer << std::endl;
           }
        }
        else
            break;
    }
         close(_sock);
    return 0;
}